package com.wise.controller.server;

import com.wise.domain.User;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/users")
public class ServerController {
    /**
     * 注意：为了方便才在controller，里面定义属性变量count与storage(否则就要通过Scope形成多例)，一般为了避免混淆
     * 纠结，请不要这样操作，也没必要
     * <p>
     * 虽然controller是单例(通常单例是线程不安全的，再啰嗦一句：与此相对多例是线程安全的)，
     * 但是(spring 通过threadlocal来解决线程安全问题，基本上单例是线程安全的。
     * spring通过对每个request进行threadlocal封装保证每个request都是独立的线程，这样来做线程安全--来源网络)
     * 所以controller多个请求并发访问单例的controller时，是不会排队，阻塞的.
     */
    private static AtomicInteger count = new AtomicInteger(0);
    private static Map<Integer, User> storage = new ConcurrentHashMap();

    /**
     * 注意：请勿模仿,这个静态代码块椒违规操作
     */
    static {
        User user = new User();
        user.setName("赵云");
        user.setAddr("长坂坡");
        int id = count.getAndIncrement();
        user.setId(id);
        storage.put(id, user);

        User user2 = new User();
        user2.setName("张飞");
        user2.setAddr("燕人");
        int id2 = count.getAndIncrement();
        user2.setId(id2);
        storage.put(id2, user2);
    }

    @GetMapping("/{id}")
    public User getUser(@PathVariable(value = "id") String id) {
        return storage.get(Integer.parseInt(id));
    }

    @GetMapping("")
    public List<User> getList() {
        List<User> list = new ArrayList<>(storage.values());
        for (int i = 0; i < list.size(); i++) {
            System.out.println("client:" + list.get(i));
        }
        return list;
    }

    @PostMapping("")
    public User receiveInfo(@RequestBody User user) {
        int count = ServerController.count.getAndIncrement();
        user.setId(count);
        storage.put(count, user);
        System.out.println("Post get the data:" + user.toString());
        return user;
    }

    @PostMapping("/{type}")
    //@RequestMapping("/{type}")
    public String receiveByType(@RequestBody User user, @PathVariable(value = "type") String type) {
        int count = ServerController.count.getAndIncrement();
        user.setId(count);
        storage.put(count, user);
        if (type != null) {
            if ("north".equals(type)) {
                return "north:" + user;
            }
            if ("south".equals(type)) {
                return "south->:" + user;
            }
        }
        return "null";
    }
}

